package com.wdb.modules.system.rest;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wdb.exception.BadRequestException;
import com.wdb.modules.system.domain.Role;
import com.wdb.modules.system.domain.vo.RoleQueryCriteria;
import com.wdb.modules.system.service.RoleService;
import com.wdb.utils.PageResult;
import com.wdb.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: wendaobai@qq.com
 * @date: 2024/3/20 0020 14:51
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "角色管理")
@RequestMapping("/api/roles")
@Slf4j
public class RoleController {
  @Autowired RoleService roleService;

  @ApiOperation("查询角色")
  @GetMapping
  public ResponseEntity<PageResult<Role>> queryRole(RoleQueryCriteria criteria, Page<Object> page) {
    log.info("query:{},page:{}", criteria, page.toString());
    PageResult<Role> pageResult = roleService.queryAll(criteria, page);
    return new ResponseEntity<>(pageResult, HttpStatus.OK);
  }

  @ApiOperation("导出")
  @GetMapping("/download")
  public void download(RoleQueryCriteria criteria, HttpServletResponse response) throws Exception {
    List<Role> roleList = roleService.queryAll(criteria);
    log.info("roleList--{}", roleList);
    // roleService.download(roleList, response);
    roleService.easyDownload(roleList, response);
  }
  // @Log("新增角色")
  @ApiOperation("新增角色")
  @PostMapping
  public ResponseEntity<Object> createRole(@RequestBody Role role) {
    if (role.getId() != null) {
      throw new BadRequestException("该角色已经存在");
    }
    roleService.create(role);
    log.info("loginfo:{}", role);
    return new ResponseEntity<>(HttpStatus.OK);
  }

  @ApiOperation("角色删除")
  @DeleteMapping
  public ResponseEntity<Object> deleteRole(@RequestBody List<Integer> ids) {
    log.info("ids:{}", ids);
    // 校验lv权限
    for (Integer id : ids) {
      Role role = roleService.getById(id);
      getLevels(role.getLevel());
    }
    // 验证是否被用户关联，有关联账号不能删除相关角色
    roleService.verification(ids);
    roleService.delete(ids);
    return new ResponseEntity<>(HttpStatus.OK);
  }

  @ApiOperation("获取用户级别")
  @GetMapping(value = "/level")
  public ResponseEntity<Object> getRoleLevel() {
    int lv = getLevels(null);
    Dict dict = Dict.create().set("level", lv);
    return new ResponseEntity<>(dict, HttpStatus.OK);
  }

  private int getLevels(Integer level) {
    List<Role> roleList = roleService.findByUsersId(SecurityUtils.getCurrentUserId());
    List<Integer> levels = roleList.stream().map(Role::getLevel).collect(Collectors.toList());
    Integer min = Collections.min(levels);
    if (level != null) {
      if (level < min) {
        throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
      }
    }
    return min;
  }
}
